package com.mvc.app.testClasses.controllers;

import com.container.app.annotations.ControllerComponent;
import com.mvc.app.Model;
import com.mvc.app.ModelView;
import com.mvc.app.annotations.BeanName;
import com.mvc.app.annotations.ControllerMethod;
import com.mvc.app.testClasses.models.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/28/12
 * Time: 10:56 AM
 */
@ControllerComponent(name = "userController")
public class UserController {

    private Date lastLogin;

    public UserController() {
    }


    @SuppressWarnings("UnusedDeclaration")
    @ControllerMethod(name = "welcome")
    public ModelView getWelcomePage(HttpServletRequest request, HttpServletResponse response, @BeanName(name = "user") User user) {
        ModelView modelView = new ModelView();
        Model model = new Model();

        makeModel(user, model);

        makeModelView(modelView, model);

        return modelView;

    }

    private void makeModelView(ModelView modelView, Model model) {

        modelView.setHtmlViewFileName("welcome_page.html");
        modelView.setModel(model);
    }

    private void makeModel(User user, Model model) {
        Map<String, Object> beans = new HashMap<String, Object>(), properties = new HashMap<String, Object>();
        beans.put("user", user);

        putLastLoginProperty(properties);

        model.addBeans(beans);
        model.addProperties(properties);
    }

    private void putLastLoginProperty(Map<String, Object> properties) {

        if (lastLogin == null)
            properties.put("last_login", "Never");
        else
            properties.put("last_login", lastLogin);

        lastLogin = new Date();
    }


}
